package fu.k4c.vTeam.ViewDetails;

import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.google.gson.Gson;

import fu.k4c.vTeam.R;
import fu.k4c.vTeam.Controller.VlocationItemizedOverlay;
import fu.k4c.vTeam.Object.Favorite;
import fu.k4c.vTeam.Route.RouterActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MapViewActivity extends MapActivity {
	Boolean visted;
	Boolean liked;
	String email;
	String PlaceID;
	Bundle data;
	int slong, slat, report;
	VlocationItemizedOverlay mMyOverlay;
	MapView mMapview;
	private static final int DIALOG_REPORT = 1;
	int CURRENT_TAG = 0;
	static final int TAG_GUEST = 0;
	static final int TAG_USER = 1;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tab_view_place_map);
		Bundle data = getIntent().getExtras();
		Double mlat = Double.parseDouble(data.getString("lat"));
		Double mlong = Double.parseDouble(data.getString("long"));
		email = data.getString("email");
		report = data.getInt("report");
		PlaceID = data.getString("IDofItemRevision");
		if (email.equals("Guest")) {
			CURRENT_TAG = TAG_GUEST;
		} else {
			CURRENT_TAG = TAG_USER;
		}
		slat = (int) (mlat * 1000000);
		slong = (int) (mlong * 1000000);
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);
		Button btn_route = (Button) findViewById(R.id.btn_view_map_route);
		Button btn_report = (Button) findViewById(R.id.btn_view_map_report);
		btn_route.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(MapViewActivity.this,
						RouterActivity.class);
				i.putExtra("lat", slat);
				i.putExtra("long", slong);
				startActivity(i);
			}
		});
		btn_report.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (CURRENT_TAG == TAG_GUEST) {
					Toast.makeText(
							getApplicationContext(),
							"Bạn phải đăng nhập để có thể sử dụng chức năng này",
							Toast.LENGTH_LONG).show();
				} else {
					if (report == 2) {
						Toast.makeText(
								getApplicationContext(),
								"Bạn không thể gửi báo cáo tới địa điểm do bạn tạo ra",
								Toast.LENGTH_LONG).show();
					} else if (report == 1) {
						Toast.makeText(
								getApplicationContext(),
								"Bạn đã gửi báo cáo về địa điểm này nên không thể gửi báo cáo thêm lần nữa",
								Toast.LENGTH_LONG).show();
					} else {
						showDialog(DIALOG_REPORT);
					}
				}
			}
		});
		mMapview = (MapView) findViewById(R.id.map_activity);
		mMapview.getController().setZoom(14);
		mMapview.setSatellite(false);
		// Truyen vao long lat o day
		GeoPoint p = new GeoPoint(slat, slong);
		// GeoPoint p = new GeoPoint(10830608,106631927);
		mMapview.getController().animateTo(p);
		mMyOverlay = new VlocationItemizedOverlay(this.getResources()
				.getDrawable(R.drawable.point));
		OverlayItem newplace = new OverlayItem(p, "New Place", "New Location");
		mMyOverlay.addOverlay(newplace);
		mMapview.getOverlays().add(mMyOverlay);
		mMapview.invalidate();
		mMapview.setOnTouchListener(new OnTouchListener() {

			public boolean onTouch(View v, MotionEvent ev) {
				// TODO Auto-generated method stub
				switch (ev.getAction()) {
				case MotionEvent.ACTION_DOWN:
					mMapview.requestDisallowInterceptTouchEvent(true);
					break;
				case MotionEvent.ACTION_UP:
					mMapview.requestDisallowInterceptTouchEvent(false);
					break;
				}
				return false;
			}
		});
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_REPORT:
			// This example shows how to add a custom layout to an AlertDialog
			LayoutInflater factory = LayoutInflater.from(this);
			final View textEntryView = factory.inflate(R.layout.report_dialog,
					null);
			return new AlertDialog.Builder(MapViewActivity.this)
					.setIcon(R.drawable.alert_dialog_icon)
					.setTitle("Báo cáo sai phạm")
					.setView(textEntryView)
					.setPositiveButton("Gửi báo cáo",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									EditText et_report = (EditText) textEntryView
											.findViewById(R.id.report_dialog_comment);
									if (et_report.getText().toString().trim()
											.length() <= 10) {
										Toast.makeText(
												MapViewActivity.this,
												"Vui lòng nhập nhiều hơn 10 ký tự",
												Toast.LENGTH_LONG).show();
									} else {
										try {
											SchemeRegistry registry = new SchemeRegistry();
											registry.register(new Scheme(
													"http",
													PlainSocketFactory
															.getSocketFactory(),
													80));
											HttpParams httpParams = new BasicHttpParams();
											ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
													httpParams, registry);
											HttpClient client = new DefaultHttpClient(
													connMgr, httpParams);
											HttpPost post = new HttpPost(
													getString(R.string.connectionString)
															+ "vLocationService/ReportItems");
											post.setHeader("Accept",
													"application/json");
											post.setHeader("Content-type",
													"application/json");
											HashMap<String, Object> postParameters = new HashMap<String, Object>();
											postParameters.put("UserName",
													email);
											postParameters.put("PlaceID",
													PlaceID);
											postParameters.put("Reason",
													et_report.getText()
															.toString().trim());
											Gson gson = new Gson();
											String jsonParameters = gson
													.toJson(postParameters);
											post.setEntity(new StringEntity(
													jsonParameters));
											HttpResponse response = client
													.execute(post);
											HttpEntity entity = response
													.getEntity();
											String jsonresult = EntityUtils
													.toString(entity);
											Favorite fvr = gson.fromJson(
													jsonresult, Favorite.class);
											if (fvr.getStatus().equals("True")) {
												report = 1;
												Toast.makeText(
														getApplicationContext(),
														"Đã gửi báo cáo thành công. Báo cáo của bạn đang được duyệt. Xin cảm ơn",
														Toast.LENGTH_LONG)
														.show();
											} else {
												Toast.makeText(
														getApplicationContext(),
														"Bạn đã gửi báo cáo về địa điểm này nên không thể gửi báo cáo thêm lần nữa",
														Toast.LENGTH_LONG)
														.show();
											}
										} catch (Exception e) {
											// TODO: handle exception
										}

									}

								}
							})
					.setNegativeButton("Hủy",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/* User clicked cancel so do some stuff */
								}
							}).create();
		}

		return null;

	}
}
